package com.nari.ncps.screen.service.impl.electric;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.electric.ElectricOpermonEquipUse;
import com.nari.ncps.screen.mapper.electric.ElectricOpermonPlantMapper;
import com.nari.ncps.screen.service.electric.ElectricOpermonEquipUseService;
import com.nari.ncps.screen.service.electric.ElectricOpermonPlantService;
import com.nari.ncps.screen.vo.electric.PlantCapacityStatistics;
import com.nari.ncps.screen.vo.electric.PlantOperationMonitorVO;
import com.nari.ncps.screen.entity.electric.ElectricOpermonPlant;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 火电运行监控电厂表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-09-24
 */
@Service
public class ElectricOpermonPlantServiceImpl extends ServiceImpl<ElectricOpermonPlantMapper, ElectricOpermonPlant> implements ElectricOpermonPlantService {

    @Resource
    private ElectricOpermonEquipUseService electricOpermonEquipUseService;

    @Override
    public List<PlantCapacityStatistics> getPlantCapacityStatistics(Integer year) {
        // 如果year为空，使用当前年份
        if (year == null) {
            year = java.time.LocalDate.now().getYear();
        }
        
        // 查询指定年份的所有数据
        QueryWrapper<ElectricOpermonPlant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year", year);
        queryWrapper.orderBy(true, false, "month"); // 按月份倒序排列
        List<ElectricOpermonPlant> plantList = list(queryWrapper);
        
        if (plantList == null || plantList.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 按电厂编码分组，取每个电厂最新月份的数据
        Map<String, ElectricOpermonPlant> latestPlantDataMap = plantList.stream()
                .collect(Collectors.toMap(
                        ElectricOpermonPlant::getOrgCode,
                        plant -> plant,
                        (existing, replacement) -> {
                            // 取月份更大的数据（已按月份倒序，第一个就是最新的）
                            if (replacement.getMonth() != null && existing.getMonth() != null 
                                && replacement.getMonth() > existing.getMonth()) {
                                return replacement;
                            }
                            return existing;
                        }
                ));
        
        // 转换为VO对象
        List<PlantCapacityStatistics> resultList = new ArrayList<>();
        for (ElectricOpermonPlant plant : latestPlantDataMap.values()) {
            PlantCapacityStatistics statistics = new PlantCapacityStatistics();
            statistics.setPlantCode(plant.getOrgCode());
            statistics.setPlantName(plant.getOrgName());
            statistics.setTotalCapacity(plant.getTotalCapacity() != null ? plant.getTotalCapacity() : BigDecimal.ZERO);
            statistics.setOperatingCapacity(plant.getOperatingCapacity() != null ? plant.getOperatingCapacity() : BigDecimal.ZERO);
            statistics.setOutageCapacity(plant.getOutageCapacity() != null ? plant.getOutageCapacity() : BigDecimal.ZERO);
            statistics.setOperationRate(plant.getOperationRate() != null ? plant.getOperationRate() : BigDecimal.ZERO);
            resultList.add(statistics);
        }
        
        // 按电厂编码排序
        resultList.sort((a, b) -> a.getPlantCode().compareTo(b.getPlantCode()));
        
        return resultList;
    }

    @Override
    public PlantOperationMonitorVO getPlantOperationMonitor(String orgCode) {
        if(orgCode== null){
            orgCode="10000166";
        }
        // 获取当前年月
//        Date now = new Date();
//        Integer year = DateUtil.year(now);
//        Integer month = DateUtil.month(now) + 1; // hutool月份从0开始，需要+1

        PlantOperationMonitorVO result = new PlantOperationMonitorVO();

        // 如果没有传入orgCode，查询第一条数据
        LambdaQueryWrapper<ElectricOpermonPlant> plantWrapper = new LambdaQueryWrapper<>();
//        plantWrapper.eq(ElectricOpermonPlant::getYear, year);
//        plantWrapper.eq(ElectricOpermonPlant::getMonth, month);
        plantWrapper.eq(ElectricOpermonPlant::getDateType, 1); // 月数据
        if (orgCode != null && !orgCode.isEmpty()) {
            plantWrapper.eq(ElectricOpermonPlant::getOrgCode, orgCode);
        }
        plantWrapper.orderByDesc(ElectricOpermonPlant::getStatisticTime);
        plantWrapper.last("LIMIT 1");

        ElectricOpermonPlant plant = getOne(plantWrapper);

        if (plant == null) {
            // 如果当前月没有数据，查询最近的一条数据
            LambdaQueryWrapper<ElectricOpermonPlant> fallbackWrapper = new LambdaQueryWrapper<>();
            if (orgCode != null && !orgCode.isEmpty()) {
                fallbackWrapper.eq(ElectricOpermonPlant::getOrgCode, orgCode);
            }
            fallbackWrapper.eq(ElectricOpermonPlant::getDateType, 1);// 月数据
            fallbackWrapper.orderByDesc(ElectricOpermonPlant::getYear,
                    ElectricOpermonPlant::getMonth,
                    ElectricOpermonPlant::getStatisticTime);
            fallbackWrapper.last("LIMIT 1");
            plant = getOne(fallbackWrapper);
        }

//        if (plant != null) {
//            result.setPlantCode(plant.getOrgCode());
//            result.setPlantName(plant.getOrgName());
//            result.setOperatingCapacity(plant.getOperatingCapacity() != null ? plant.getOperatingCapacity() : BigDecimal.ZERO);
//            result.setOutageCapacity(plant.getOutageCapacity() != null ? plant.getOutageCapacity() : BigDecimal.ZERO);
//            result.setInstalledCapacity(plant.getTotalCapacity() != null ? plant.getTotalCapacity() : BigDecimal.ZERO);
//
//            // 查询设备信息获取运行机组台数、停机台数和利用小时数
//            LambdaQueryWrapper<ElectricOpermonEquipUse> equipWrapper = new LambdaQueryWrapper<>();
//            equipWrapper.eq(ElectricOpermonEquipUse::getYear, plant.getYear());
//            equipWrapper.eq(ElectricOpermonEquipUse::getMonth, plant.getMonth());
//            equipWrapper.eq(ElectricOpermonEquipUse::getDateType, 1); // 月数据
//            if (plant.getOrgCode() != null && !plant.getOrgCode().isEmpty()) {
//                equipWrapper.eq(ElectricOpermonEquipUse::getOrgCode, plant.getOrgCode());
//            }
//            equipWrapper.orderByDesc(ElectricOpermonEquipUse::getUpdateTime);
//            equipWrapper.last("LIMIT 1");
//
//            ElectricOpermonEquipUse equipUse = electricOpermonEquipUseService.getOne(equipWrapper);
//
//            if (equipUse != null) {
//                result.setRunningUnits(equipUse.getRunningUnits() != null ? equipUse.getRunningUnits() : 0);
//
//                // 停机台数 = 备用台数 + 检修台数
//                Integer standbyUnits = equipUse.getStandbyUnits() != null ? equipUse.getStandbyUnits() : 0;
//                Integer maintenanceUnits = equipUse.getMaintenanceUnits() != null ? equipUse.getMaintenanceUnits() : 0;
//                result.setOutageUnits(standbyUnits + maintenanceUnits);
//
//                result.setUtilizationHours(equipUse.getUsageHours() != null ? equipUse.getUsageHours() : BigDecimal.ZERO);
//            } else {
//                result.setRunningUnits(0);
//                result.setOutageUnits(0);
//                result.setUtilizationHours(BigDecimal.ZERO);
//            }
//        }

        return result;
    }

}
